package com.titar.robot.ui.welcom;



import com.titar.robot.AppExecutors;
import com.titar.robot.db.CacheTableDao;
import com.titar.robot.db.RobotDatabase;
import com.titar.robot.entity.MemberInfo;
import com.titar.robot.http.RetrofitApi;
import com.titar.robot.http.service.CustomerService;
import com.titar.robot.repository.Resource;

import androidx.lifecycle.Observer;



public class WelcomePresenter implements WelcomeContact.Presenter {
    private WelcomeContact.View v;
    private WelcomeRepository welcomeRepository;

    public WelcomePresenter() {
        AppExecutors appExecutors = AppExecutors.getInstence();
        CacheTableDao cacheTableDao = RobotDatabase.getDatabase().cacheTableDao();
        CustomerService customerService = RetrofitApi.getRequestInterface();
        welcomeRepository = new WelcomeRepository(appExecutors, cacheTableDao, customerService);
    }

    @Override
    public void checkToken(String token) {
        welcomeRepository.checkToken(token)
                .observeForever(new Observer<Resource<MemberInfo>>() {
                    @Override
                    public void onChanged(Resource<MemberInfo> stringResource) {
                        switch (stringResource.getStatus()) {
                            case ERROR:
                                if (v != null) {
                                    v.dismissLoadingDialog();
                                    v.showErrorDialog( stringResource.getMessage(), false);
                                }

                                break;
                            case RESULT_ERROR:
                                if (v != null) {
                                    v.dismissLoadingDialog();
                                    v.onTokenResult(false);
                                }

                                break;
                            case LOADING:
                                if (v != null) {
                                    v.showLoadingDialog();
                                }
                                break;
                            case SUCCESS:
                                if (v != null) {
                                    v.dismissLoadingDialog();
                                    v.onTokenResult(true);
                                }
                                break;
                        }
                    }
                });
    }

    @Override
    public WelcomeContact.Presenter attachView(WelcomeContact.View view) {
        this.v = view;
        return this;
    }

    @Override
    public void detachView() {
        this.v = null;
    }
}
